<template>
  <div class="consult-container">
    <!-- 医生列表 -->
    <el-card class="doctor-list" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>在线医生</span>
        </div>
      </template>
      <el-empty v-if="doctors.length === 0" description="暂无在线医生" />
      <template v-else>
        <el-row :gutter="20">
          <el-col :span="8" v-for="doctor in currentPageDoctors" :key="doctor.id">
            <el-card class="doctor-card" shadow="hover">
              <div class="doctor-info">
                <el-avatar :size="64" :src="doctor.avatar" />
                <div class="info-content">
                  <h3>{{ doctor.name }}</h3>
                  <p class="title">{{ doctor.title }}</p>
                  <p class="department">{{ doctor.department }}</p>
                </div>
              </div>
              <div class="doctor-introduction">
                {{ doctor.introduction }}
              </div>
              <el-button 
                type="primary" 
                round 
                @click="handleConsult(doctor)"
                :disabled="doctor.status !== 1"
              >
                {{ doctor.status === 1 ? '立即问诊' : '停诊中' }}
              </el-button>
            </el-card>
          </el-col>
        </el-row>
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="doctors.length"
            layout="prev, pager, next"
            background
            @current-change="handlePageChange"
          />
        </div>
      </template>
    </el-card>

    <!-- 预约对话框 -->
    <el-dialog
      v-model="consultDialogVisible"
      title="预约问诊"
      width="500px"
    >
      <el-form :model="consultForm" label-width="100px">
        <el-form-item label="就诊人">
          <el-select v-model="consultForm.childId" placeholder="请选择就诊人">
            <el-option
              v-for="child in children"
              :key="child.id"
              :label="child.name"
              :value="child.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="咨询标题">
          <el-input v-model="consultForm.title" placeholder="请输入咨询标题" />
        </el-form-item>
        <el-form-item label="咨询类型">
          <el-select v-model="consultForm.consultationType" placeholder="请选择咨询类型">
            <el-option label="生长发育" value="growth" />
            <el-option label="营养" value="nutrition" />
            <el-option label="心理" value="psychology" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="咨询内容">
          <el-input
            v-model="consultForm.content"
            type="textarea"
            rows="4"
            placeholder="请详细描述咨询内容..."
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="consultDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitConsult">
            确认预约
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 问诊记录和统计 -->
    <el-card class="consult-stats">
      <template #header>
        <div class="card-header">
          <span>问诊记录</span>
          <div class="filter-buttons">
            <el-radio-group v-model="currentStatus" @change="handleStatusChange">
              <el-radio-button :label="-1">全部</el-radio-button>
              <el-radio-button :label="0">未回复</el-radio-button>
              <el-radio-button :label="1">已回复</el-radio-button>
              <el-radio-button :label="2">已关闭</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="stats-card">
            <div class="stats-icon waiting">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stats-info">
              <h4>未回复</h4>
              <div class="stats-number">{{ consultStats.notReplied || 0 }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stats-card">
            <div class="stats-icon processing">
              <el-icon><ChatDotRound /></el-icon>
            </div>
            <div class="stats-info">
              <h4>已回复</h4>
              <div class="stats-number">{{ consultStats.replied || 0 }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stats-card">
            <div class="stats-icon finished">
              <el-icon><CircleCheckFilled /></el-icon>
            </div>
            <div class="stats-info">
              <h4>已关闭</h4>
              <div class="stats-number">{{ consultStats.closed || 0 }}</div>
            </div>
          </div>
        </el-col>
      </el-row>
      
      <!-- 最近问诊记录 -->
      <div class="recent-consults">
        <el-empty v-if="filteredConsults.length === 0" description="暂无问诊记录" />
        <div v-else class="consult-timeline">
          <el-timeline>
            <el-timeline-item
              v-for="consult in filteredConsults"
              :key="consult.id"
              :timestamp="formatDate(consult.createTime)"
              :type="getStatusType(consult.status)"
            >
              <template v-slot:default>
                <div class="timeline-content">
                  <div class="consult-header">
                    <el-tag size="small" :type="getConsultationType(consult.consultationType)">
                      {{ getConsultationTypeText(consult.consultationType) }}
                    </el-tag>
                    <h4>{{ consult.title }}</h4>
                  </div>
                  <div class="expert-info">
                    <span class="expert-name">{{ getExpertInfo(consult.expertId).name }}</span>
                    <span class="expert-title">{{ getExpertInfo(consult.expertId).title }}</span>
                    <span class="expert-department">{{ getExpertInfo(consult.expertId).department }}</span>
                  </div>
                  <p class="description">{{ consult.content }}</p>
                  <p class="reply" v-if="consult.doctorReply">
                    医生回复：{{ consult.doctorReply }}
                    <span class="reply-time" v-if="consult.replyTime">
                      ({{ formatDate(consult.replyTime) }})
                    </span>
                  </p>
                  <div class="timeline-footer">
                    <el-tag :type="getStatusTag(consult.status)">
                      {{ getStatusText(consult.status) }}
                    </el-tag>
                    <el-button 
                      v-if="consult.status === 0" 
                      type="primary" 
                      link
                      @click="viewConsultDetail(consult.id)"
                    >
                      查看详情
                    </el-button>
                  </div>
                </div>
              </template>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-card>

    <!-- 问诊详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="问诊详情"
      width="600px"
      class="consult-detail-dialog"
    >
      <template v-slot:default>
        <div v-if="currentConsult" class="consult-detail">
          <div class="detail-header">
            <el-tag size="small" :type="getConsultationType(currentConsult.consultationType)">
              {{ getConsultationTypeText(currentConsult.consultationType) }}
            </el-tag>
            <h3>{{ currentConsult.title }}</h3>
            <div class="expert-info">
              <span class="expert-name">{{ getExpertInfo(currentConsult.expertId).name }}</span>
              <span class="expert-title">{{ getExpertInfo(currentConsult.expertId).title }}</span>
              <span class="expert-department">{{ getExpertInfo(currentConsult.expertId).department }}</span>
            </div>
            <p class="create-time">提交时间：{{ formatDate(currentConsult.createTime) }}</p>
          </div>
          
          <div class="detail-content">
            <div class="content-section">
              <h4>咨询内容：</h4>
              <p>{{ currentConsult.content }}</p>
            </div>
            
            <div class="reply-section" v-if="currentConsult.doctorReply">
              <h4>医生回复：</h4>
              <div class="reply-content">
                <p>{{ currentConsult.doctorReply }}</p>
                <p class="reply-time" v-if="currentConsult.replyTime">
                  回复时间：{{ formatDate(currentConsult.replyTime) }}
                </p>
              </div>
            </div>
            
            <div class="status-section">
              <el-tag :type="getStatusTag(currentConsult.status)">
                {{ getStatusText(currentConsult.status) }}
              </el-tag>
            </div>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import {
  Clock,
  ChatDotRound,
  CircleCheckFilled
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { get, post } from '@/utils/request'
import { getToken, parseToken } from '@/utils/auth'

// 医生列表
const doctors = ref([])
const loading = ref(false)

// 专家信息缓存
const expertsMap = ref(new Map())

// 获取专家列表
const fetchDoctors = async () => {
  try {
    loading.value = true
    const res = await get('/user/expert/list')
    console.log('专家列表数据:', res)
    doctors.value = Array.isArray(res) ? res.filter(doctor => doctor.status === 1) : []
    // 构建专家信息映射
    doctors.value.forEach(doctor => {
      expertsMap.value.set(doctor.id, doctor)
    })
  } catch (error) {
    console.error('获取专家列表失败:', error)
    ElMessage.error('获取专家列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取专家信息的函数
const getExpertInfo = (expertId) => {
  return expertsMap.value.get(expertId) || { name: '未知医生', title: '', department: '' }
}

// 就诊人列表
const children = ref([])

// 获取就诊人列表
const fetchChildren = async () => {
  try {
    const res = await get('/user/child/list')
    children.value = Array.isArray(res) ? res : []
    if (children.value.length === 0) {
      ElMessage.warning('您还没有添加就诊人，请先添加就诊人')
    }
  } catch (error) {
    console.error('获取就诊人列表失败:', error)
    ElMessage.error('获取就诊人列表失败，请稍后重试')
  }
}

// 预约对话框
const consultDialogVisible = ref(false)
const consultForm = reactive({
  childId: '',
  expertId: '',
  title: '',
  content: '',
  consultationType: '',
})

// 选择医生进行问诊
const handleConsult = (doctor) => {
  if (doctor.status !== 1) {
    ElMessage.warning('该医生目前停诊')
    return
  }
  consultForm.expertId = doctor.id
  consultDialogVisible.value = true
}

// 提交预约
const handleSubmitConsult = async () => {
  if (!consultForm.childId) {
    ElMessage.warning('请选择就诊人')
    return
  }
  if (!consultForm.title.trim()) {
    ElMessage.warning('请输入咨询标题')
    return
  }
  if (!consultForm.consultationType) {
    ElMessage.warning('请选择咨询类型')
    return
  }
  if (!consultForm.content.trim()) {
    ElMessage.warning('请输入咨询内容')
    return
  }

  try {
    // 从token中获取用户ID
    const token = getToken()
    const tokenInfo = parseToken(token)
    if (!tokenInfo || !tokenInfo.id) {
      ElMessage.error('用户信息获取失败，请重新登录')
      return
    }

    const data = {
      expertId: consultForm.expertId,
      childId: consultForm.childId,
      userId: tokenInfo.id,
      title: consultForm.title.trim(),
      content: consultForm.content.trim(),
      consultationType: consultForm.consultationType
    }

    await post('/user/consultation/create', data)
    ElMessage.success('预约成功')
    consultDialogVisible.value = false
    // 重置表单
    Object.assign(consultForm, {
      childId: '',
      expertId: '',
      title: '',
      content: '',
      consultationType: ''
    })
    // 重新获取问诊记录
    fetchConsultStats()
  } catch (error) {
    console.error('预约失败:', error)
    ElMessage.error('预约失败，请稍后重试')
  }
}

// 分页相关
const pageSize = ref(3) // 每页显示3条
const currentPage = ref(1) // 当前页码

// 计算当前页的医生列表
const currentPageDoctors = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return doctors.value.slice(start, end)
})

// 页码改变处理
const handlePageChange = (page) => {
  currentPage.value = page
}

// 问诊统计数据
const consultStats = ref({
  notReplied: 0, // 未回复数量
  replied: 0,    // 已回复数量
  closed: 0      // 已关闭数量
})

// 最近问诊记录
const recentConsults = ref([])

// 当前选中的状态过滤
const currentStatus = ref(-1) // -1 表示全部

// 根据状态筛选的问诊记录
const filteredConsults = computed(() => {
  if (currentStatus.value === -1) {
    return recentConsults.value
  }
  return recentConsults.value.filter(consult => consult.status === currentStatus.value)
})

// 状态切换处理
const handleStatusChange = (value) => {
  currentStatus.value = value
}

// 获取问诊记录
const fetchConsultStats = async () => {
  try {
    const res = await get('/user/consultation/list')
    console.log('问诊记录数据:', res) // 添加调试日志
    
    // 直接使用返回的数据，不需要判断 res.code
    const consultations = res || []
    
    // 计算统计数据
    const stats = {
      notReplied: consultations.filter(c => c.status === 0).length,
      replied: consultations.filter(c => c.status === 1).length,
      closed: consultations.filter(c => c.status === 2).length
    }
    consultStats.value = stats
    
    // 保存所有记录
    recentConsults.value = consultations.sort((a, b) => 
      new Date(b.createTime) - new Date(a.createTime)
    )
  } catch (error) {
    console.error('获取问诊记录失败:', error)
    ElMessage.error('获取问诊记录失败，请稍后重试')
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    0: 'warning',
    1: 'success',
    2: 'info'
  }
  return types[status] || 'info'
}

// 获取状态标签类型
const getStatusTag = (status) => {
  const tags = {
    0: 'warning',
    1: 'success',
    2: 'info'
  }
  return tags[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '待回复',
    1: '已回复',
    2: '已关闭'
  }
  return texts[status] || '未知状态'
}

// 详情对话框相关
const detailDialogVisible = ref(false)
const currentConsult = ref(null)

// 查看问诊详情
const viewConsultDetail = async (consultId) => {
  try {
    const res = await get(`/user/consultation/detail/${consultId}`)
    // 直接使用返回的数据
    currentConsult.value = res
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取问诊详情失败:', error)
    ElMessage.error('获取问诊详情失败，请稍后重试')
  }
}

// 获取咨询类型标签样式
const getConsultationType = (type) => {
  const types = {
    'growth': 'success',
    'nutrition': 'warning',
    'psychology': 'danger',
    'other': 'info'
  }
  return types[type] || 'info'
}

// 获取咨询类型文本
const getConsultationTypeText = (type) => {
  const texts = {
    'growth': '生长发育',
    'nutrition': '营养',
    'psychology': '心理',
    'other': '其他'
  }
  return texts[type] || '其他'
}

// 格式化时间
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 页面加载时获取专家列表和就诊人列表
onMounted(() => {
  fetchDoctors()
  fetchChildren()
  fetchConsultStats()
})
</script>

<style>
:root {
  height: 100%;
  overflow-y: auto;
}

body {
  min-height: 100%;
  margin: 0;
  padding: 0;
  overflow-y: auto;
}
</style>

<style scoped>
.consult-container {
  padding: 24px;
  min-height: 100%;
  position: relative;
}

.doctor-list {
  margin-bottom: 24px;
  border-radius: 16px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 18px;
  font-weight: 600;
}

.doctor-card {
  margin-bottom: 20px;
}

.doctor-info {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
}

.info-content {
  margin-left: 16px;
}

.info-content h3 {
  margin: 0 0 8px;
  font-size: 18px;
}

.info-content .title {
  margin: 0 0 4px;
  color: #409eff;
  font-size: 14px;
}

.info-content .department {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

:deep(.el-dialog) {
  border-radius: 16px;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
}

.doctor-introduction {
  margin: 16px 0;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.el-empty {
  padding: 40px 0;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #409eff;
}

:deep(.el-pagination.is-background .el-pager li) {
  margin: 0 4px;
  min-width: 32px;
  border-radius: 4px;
}

.consult-stats {
  margin-bottom: 24px;
  border-radius: 16px;
  overflow: hidden;
}

.stats-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
  transition: all 0.3s;
}

.stats-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stats-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
}

.stats-icon.waiting {
  background: #fff7e6;
  color: #faad14;
}

.stats-icon.processing {
  background: #e6f7ff;
  color: #1890ff;
}

.stats-icon.finished {
  background: #f6ffed;
  color: #52c41a;
}

.stats-info h4 {
  margin: 0 0 8px;
  font-size: 14px;
  color: #666;
}

.stats-number {
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.recent-consults {
  margin-top: 24px;
}

.consult-timeline {
  padding: 20px 0;
}

.consult-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.consult-header h4 {
  margin: 0;
  flex: 1;
}

.timeline-content {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.timeline-content .description {
  background: #fafafa;
  padding: 12px;
  border-radius: 4px;
  margin: 12px 0;
}

.timeline-footer {
  margin-top: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-timeline-item__node) {
  width: 12px;
  height: 12px;
}

:deep(.el-timeline-item__tail) {
  left: 5px;
}

:deep(.el-timeline-item__wrapper) {
  padding-left: 28px;
}

:deep(.el-timeline-item__timestamp) {
  font-size: 12px;
  color: #999;
}

.filter-buttons {
  display: flex;
  align-items: center;
}

:deep(.el-radio-button__inner) {
  padding: 8px 16px;
}

:deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-radius: 4px 0 0 4px;
}

:deep(.el-radio-button:last-child .el-radio-button__inner) {
  border-radius: 0 4px 4px 0;
}

.consult-detail {
  padding: 20px;
}

.detail-header {
  margin-bottom: 24px;
}

.detail-header h3 {
  margin: 12px 0;
  font-size: 20px;
  color: #333;
}

.create-time {
  color: #999;
  font-size: 14px;
  margin: 8px 0;
}

.content-section,
.reply-section {
  margin-bottom: 24px;
}

.content-section h4,
.reply-section h4 {
  color: #666;
  font-size: 16px;
  margin-bottom: 12px;
}

.content-section p {
  background: #fafafa;
  padding: 16px;
  border-radius: 8px;
  margin: 0;
  line-height: 1.6;
  color: #333;
}

.reply-content {
  background: #e6f7ff;
  padding: 16px;
  border-radius: 8px;
  color: #1890ff;
}

.reply-time {
  margin-top: 8px;
  font-size: 14px;
  color: #666;
}

.status-section {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-dialog__body) {
  padding: 0;
}

.timeline-content .reply {
  background: #e6f7ff;
  padding: 12px;
  border-radius: 4px;
  margin: 12px 0;
  color: #1890ff;
}

.reply-time {
  color: #666;
  font-size: 12px;
  margin-left: 8px;
}

.reply-section {
  margin-bottom: 24px;
}

.reply-content {
  background: #e6f7ff;
  padding: 16px;
  border-radius: 8px;
  color: #1890ff;
}

.reply-content .reply-time {
  margin-top: 8px;
  font-size: 14px;
  color: #666;
}

.expert-info {
  margin: 8px 0;
  color: #666;
  font-size: 14px;
}

.expert-name {
  font-weight: 600;
  color: #333;
}

.expert-title,
.expert-department {
  margin-left: 8px;
  color: #666;
}
</style> 